package com.jftone.bh.app.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.jftone.bh.app.config.SysConst;
import com.jftone.bh.app.model.SysAdmin;
import com.jftone.bh.app.model.SysAdminRole;
import com.jftone.bh.app.model.SysLog;
import org.apache.log4j.Logger;
import org.jftone.annotation.Autowired;
import org.jftone.annotation.Service;
import org.jftone.annotation.Transactional;
import org.jftone.dao.Dao;
import org.jftone.exception.ComponentException;
import org.jftone.exception.DaoException;
import org.jftone.util.DataMap;
import org.jftone.util.IData;
import org.jftone.util.Page;


@Service
public class AdminService {
	
	private Logger logger = Logger.getLogger(AdminService.class);
	
	@Autowired
	private Dao dao;
	
	public List<SysAdmin> querySysAdmin(IData<String, Object> inData, Page page) throws ComponentException{
		List<SysAdmin> adminList = null;
		try{
			adminList = dao.query(SysAdmin.class, inData, page);
		}catch(DaoException e){
			logger.error("查询管理员信息错误"+e.getMessage(), e);
			throw new ComponentException("查询管理员信息错误"+e.getMessage(), e);
		}
		return adminList;
	}
	
	@Transactional
	public int login(SysAdmin sysAdmin) throws ComponentException{
		int resultCode = 0;
		IData<String, Object> inData = new DataMap<String, Object>();
		inData.put("adminUser", sysAdmin.getAdminUser());
		try{
			SysAdmin sa = dao.get(SysAdmin.class, inData);
			if(sa == null){
				return 1;
			}
			if(sa.getLocked() != 0) {
				return 2;
			}
			if(!sysAdmin.getPassword().equals(sa.getPassword())){
				return 3;
			}
			SysAdmin updateAdmin = new SysAdmin();
			updateAdmin.setId(sa.getId());
			updateAdmin.setLoginIp(sysAdmin.getLoginIp());
			updateAdmin.setLoginTime(sysAdmin.getLoginTime());
			dao.update(updateAdmin);
			sysAdmin.setId(sa.getId());
			sysAdmin.setUserName(sa.getUserName());
			sysAdmin.setMobile(sa.getMobile());
			sysAdmin.setEmail(sa.getEmail());
		}catch(DaoException e){
			logger.error("管理员登录错误："+e.getMessage(), e);
			throw new ComponentException(e);
		}
		return resultCode;
	}
	
	/**
	 * 保存系统管理用户
	 * @param admin
	 * @param sarList
	 * @return
	 * @throws ComponentException
	 */
	@Transactional
	public int saveAdmin(SysAdmin admin, List<SysAdminRole> sarList) throws ComponentException{
		int resultCode = 0;
		try{
			IData<String, Object> inData = new DataMap<String, Object>();
			String adminUser = admin.getAdminUser();
			//如果id为空，表示新增，需要校验是否有重复情况
			if(null == admin.getId()){
				inData.put("adminUser", adminUser);
				if(dao.count(SysAdmin.class, inData)>0){
					return 1;
				}
				dao.save(admin);
			}else{
				dao.update(admin);
				//清理角色数据
				inData.clear();
				inData.put("userNo", adminUser);
				dao.delete(SysAdminRole.class, inData);
			}
			//更新用户角色数据
			if(null != sarList && sarList.size()>0){
				dao.insertBatch(sarList);
			}
		}catch(DaoException e){
			logger.error("更新管理用户数据错误："+e.getMessage(), e);
			throw new ComponentException("更新用户数据错误："+e.getMessage(), e);
		}
		return resultCode;
	}
	
	@Transactional
	public int deleteAdmin(int adminId) throws ComponentException{
		int resultCode = 0;
		try{
			
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("id", adminId);
			SysAdmin admin = dao.get(SysAdmin.class, inData);
			if(admin == null){
				return 1;
			}
			
			inData.clear();
			inData.put("userNo", admin.getAdminUser());
			dao.delete(SysAdminRole.class, inData);
			dao.delete(admin);
			
		}catch(DaoException e){
			logger.error("删除参系统管理员数据错误："+e.getMessage(), e);
			throw new ComponentException("删除系统管理员数据错误："+e.getMessage(), e);
		}
		return resultCode;
	}
	
	public List<IData<String, Object>> queryMenuByCode(String roleCode) throws ComponentException{
		List<IData<String, Object>> moduleList = null;
		try{
			List<IData<String, Object>> mdList = new ArrayList<IData<String, Object>>();
			String[] roleCodes = roleCode.split(SysConst.SEPARATOR_COMMA);
			for(String code : roleCodes){
				IData<String, Object> tmp = new DataMap<String, Object>(); 
				tmp.put("ROLE_CODE", code);
				mdList.add(tmp);
			}
			List<IData<String, Object>> rmList = dao.queryUnion("queryModuleByRole", mdList, false);;
			List<IData<String, Object>> inList = new ArrayList<IData<String, Object>>();
			for(IData<String, Object> obj : rmList){
				inList.add(obj);
			}
			moduleList = dao.queryUnion("getMenuByCode", inList, false);
			Collections.sort(moduleList, new Comparator<IData<String, Object>>(){
				public int compare(IData<String, Object> d1, IData<String, Object> d2) {
					return d2.getShort("SEQ_SORT")-d1.getShort("SEQ_SORT");
				}
			});
		}catch(DaoException e){
			logger.error("获取系统模块错误" + e.getMessage(), e);
			throw new ComponentException("获取系统模块错误" + e.getMessage(), e);
		}
		return moduleList;
	}
	
	public List<IData<String, Object>> queryNode(String moduleCode, String roleCode) throws ComponentException{
		List<IData<String, Object>> nodeList = null;
		try{
			List<IData<String, Object>> list = new ArrayList<IData<String, Object>>();
			for(String code : roleCode.split(SysConst.SEPARATOR_COMMA)){
				IData<String, Object> inData = new DataMap<String, Object>();
				inData.put("ROLE_CODE", code);
				inData.put("MODULE_CODE", moduleCode);
				list.add(inData);
			}		
			List<IData<String, Object>> tmpList = dao.queryUnion("queryNodeByRoleModule", list, false);
			list = new ArrayList<IData<String, Object>>();
			if(null != tmpList && tmpList.size()>0){
				for(IData<String, Object> obj : tmpList){
					list.add(obj);
				}
			}
			nodeList = dao.queryUnion("getMenuByCode", list);
			if(null != nodeList && nodeList.size()>0){
				Collections.sort(nodeList, new Comparator<IData<String, Object>>(){
					public int compare(IData<String, Object> o1, IData<String, Object> o2) {
						return o2.getShort("SEQ_SORT")-o1.getShort("SEQ_SORT");
					}
				});
			}
		}catch(DaoException e){
			logger.error("获取菜单节点错误" + e.getMessage(), e);
			throw new ComponentException("获取菜单节点错误" + e.getMessage(), e);
		}
		return nodeList;
	}
	
	public List<IData<String, Object>> queryMenuList(String nodeCode, String roleCode) throws ComponentException{
		List<IData<String, Object>> menuList = null;
		try{
			List<IData<String, Object>> list = new ArrayList<IData<String, Object>>();
			for(String code : roleCode.split(",")){
				IData<String, Object> inData = new DataMap<String, Object>();
				inData.put("ROLE_CODE", code);
				inData.put("NODE_CODE", nodeCode);
				list.add(inData);
			}	
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("NODE_CODE", nodeCode);
			menuList = dao.queryUnion("queryRightByRoleNode", list, false);
			if(null != menuList && menuList.size()>0){
				Collections.sort(menuList, new Comparator<IData<String, Object>>(){
					public int compare(IData<String, Object> o1, IData<String, Object> o2) {
						return o2.getShort("SEQ_SORT")-o1.getShort("SEQ_SORT");
					}
				});
			}
		}catch(DaoException e){
			logger.error("获取菜单数据错误" + e.getMessage(), e);
			throw new ComponentException("获取菜单数据错误" + e.getMessage(), e);
		}
		return menuList;
	}
	
	public List<IData<String, Object>> querySysRole() throws ComponentException{
		List<IData<String, Object>> roleList = null;
		try{
			roleList = dao.query("querySysRole", null);
		}catch(DaoException e){
			logger.error("加载管理员角色信息错误"+e.getMessage(), e);
			throw new ComponentException("加载管理员角色信息错误"+e.getMessage(), e);
		}
		return roleList;
	}
	
	public SysAdmin getSysAdmin(IData<String, Object> inData) throws ComponentException{
		SysAdmin sysAdmin = null;
		try{
			sysAdmin = dao.get(SysAdmin.class, inData);
		}catch(DaoException e){
			logger.error("查询系统管理员数据错误"+e.getMessage(), e);
			throw new ComponentException("查询系统管理员数据错误"+e.getMessage(), e);
		}
		return sysAdmin;
	}
	
	@Transactional
	public void updateAdminPass(SysAdmin sysAdmin) throws ComponentException{
		try{
			dao.update(sysAdmin);
		}catch(DaoException e){
			logger.error("修改管理员密码信息错误："+e.getMessage(), e);
			throw new ComponentException("修改管理员密码信息错误", e);
		}
	}
	
	public List<SysAdminRole> querySysAdminRole(IData<String, Object> inData) throws ComponentException{
		List<SysAdminRole> retList = null;
		try{
			retList = dao.query(SysAdminRole.class, inData);
		}catch(DaoException e){
			logger.error("查询系统管理员角色数据错误"+e.getMessage(), e);
			throw new ComponentException("查询系统管理员角色数据错误"+e.getMessage(), e);
		}
		return retList;
	}
	
	public void saveSysLog(SysLog sysLog) throws ComponentException{
		try{
			dao.save(sysLog);
		}catch(DaoException e){
			logger.error("保存系统操作日志记录异常"+e.getMessage(), e);
			throw new ComponentException("保存系统操作日志记录异常"+e.getMessage(), e);
		}
	}
	
}
